#include "dynamic_json_ui/json_parser.h"

#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDebug>

namespace dynamic_json_ui {

struct JsonUiElement;

JsonUiElement JsonParser::parse(const QString &jsonContent)
{
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(jsonContent.toUtf8(), &error);
    if (error.error != QJsonParseError::NoError) {
        qDebug() << "JSON 解析错误：" << error.errorString();
        return {};
    }

    return parseObject(doc.object());
}

JsonUiElement JsonParser::parseObject(const QJsonObject &obj)
{
    JsonUiElement element;

    element.type = obj.value("type").toString();
    element.id = obj.value("id").toString();
    element.style = obj.value("style").toString();

    QJsonObject props = obj.value("properties").toObject();
    for (auto it = props.begin(); it != props.end(); ++it) {
        element.properties.insert(it.key(), it.value().toVariant());
    }

    QJsonArray children = obj.value("children").toArray();
    for (const auto &child : children) {
        element.children.append(parseObject(child.toObject()));
    }

    QJsonObject _signals = obj.value("on").toObject();
    for (auto it = _signals.begin(); it != _signals.end(); ++it) {
        element._signals.insert("on" + it.key(), it.value().toString());
    }

    return element;
}
} // namespace dynamic_json_ui
